package com.itheima.aspect;

import com.itheima.mapper.EmpLoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginInfo;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.Result;
import io.jsonwebtoken.Jwt;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginAspect {
    @Autowired
    private EmpLoginMapper empLoginMapper;

    @Around("execution(public * com.itheima.controller.LoginController.login(com.itheima.pojo.Emp))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("登录日志");
        Long start = System.currentTimeMillis();

        Result result = (Result)joinPoint.proceed();

        int code = result.getCode();
        Short isSuccess =(short) code;

        Object[] args = joinPoint.getArgs();
        Emp emp = (Emp) args[0];
        String username = emp.getUsername();
        String password = emp.getPassword();
        LocalDateTime loginTime = LocalDateTime.now();
        EmpLoginInfo loginInfo = (EmpLoginInfo) result.getData();
        String jwt;
        if (loginInfo==null){
            jwt="";
        }else {
            jwt = loginInfo.getToken();
        }
        Long costTime = System.currentTimeMillis() - start;
        EmpLoginLog empLoginLog=new EmpLoginLog();
        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        empLoginLog.setLoginTime(loginTime);
        empLoginLog.setIsSuccess(isSuccess);
        empLoginLog.setJwt(jwt);
        empLoginLog.setCostTime(costTime);
        empLoginMapper.insert(empLoginLog);
        return result;

    }
}
